<template>
	<view class="approval-process-container">
		<!-- 页面头部 -->
		<view class="header">
			<view class="title-container">
				<text class="icon">{{ getApplicationIcon(workflowType) }}</text>
				<text class="title">{{ getWorkflowTypeText(workflowType) }}</text>
			</view>
			<view class="status-badge" :class="getStatusClass(workflowStatus)">
				{{ getStatusText(workflowStatus) }}
			</view>
		</view>

		<!-- 申请基本信息 -->
		<view class="section basic-info">
			<view class="section-title">申请信息</view>
			<view class="info-card">
				<view class="info-item" v-if="applicantInfo.name">
					<text class="label">申请人</text>
					<text class="value">{{ applicantInfo.name }}</text>
				</view>
				<view class="info-item" v-if="applicationData.created_at">
					<text class="label">申请时间</text>
					<text class="value">{{ formatDate(applicationData.created_at) }}</text>
				</view>
				<view class="info-item detail-item"
					v-if="applicationData.business_data && applicationData.business_data.detail">
					<text class="label">申请内容</text>
					<view class="detail-content">
						<text class="detail-text">{{ applicationData.business_data.detail }}</text>
					</view>
				</view>
				<view class="info-item" v-if="timeRange">
					<text class="label">时间范围</text>
					<text class="value">{{ timeRange }}</text>
				</view>
				<!-- 申请附件 -->
				<view class="info-item detail-item" v-if="applicationAttachments && applicationAttachments.length > 0">
					<text class="label">申请附件</text>
					<view class="attachments-list">
						<view class="attachment-item" v-for="(file, fileIndex) in applicationAttachments"
							:key="fileIndex" @tap="previewFile(file)">
							<!-- 图片文件显示缩略图 -->
							<image v-if="isImageFile(file)" class="file-thumbnail" :src="file.url" mode="aspectFill" 
								@error="handleImageError" />
							<!-- 非图片文件显示图标 -->
							<text v-else class="file-icon">📎</text>
							<view class="file-info">
								<text class="file-name">{{ file.name }}</text>
								<text class="file-size" v-if="file.size">{{ file.size }}</text>
							</view>
						</view>
					</view>
				</view>

			</view>
		</view>

		<!-- 审批流程时间线 -->
		<view class="section approval-timeline">
			<view class="section-title">审批流程</view>
			<view class="timeline-container">
				<view v-if="isLoading" class="loading-state">
					<text class="loading-text">加载审批流程中...</text>
				</view>

				<view v-else-if="approvalSteps.length === 0" class="empty-state">
					<text class="empty-icon">📋</text>
					<text class="empty-text">暂无审批流程信息</text>
				</view>

				<view v-else class="timeline">
					<view class="timeline-item" v-for="(step, index) in approvalSteps" :key="index" :class="{
						'current-step': step.status === 'pending',
						'completed-step': step.status === 'approved',
						'rejected-step': step.status === 'rejected',
						'last-item': index === approvalSteps.length - 1
					}">
						<!-- 时间线连接线 -->
						<view class="timeline-line" v-if="index < approvalSteps.length - 1"></view>

						<!-- 步骤标记 -->
						<view class="step-marker" :class="getStepStatusClass(step.status)">
							<text v-if="step.status === 'approved'" class="marker-icon">✓</text>
							<text v-else-if="step.status === 'rejected'" class="marker-icon">✗</text>
							<text v-else-if="step.status === 'pending'" class="marker-icon">⏳</text>
							<text v-else class="marker-icon">○</text>
						</view>

						<!-- 步骤内容 -->
						<view class="step-content">
							<view class="step-header">
								<view class="step-info">
									<text class="step-name">{{ step.approver_name || step.user_name }}</text>
									<text class="step-position">{{ step.approver_position || '审批人' }}</text>
								</view>
								<text class="step-status" :class="getStepStatusClass(step.status)">
									{{ getStepStatusText(step.status) }}
								</text>
							</view>

							<!-- 审批时间 -->
							<view class="step-time" v-if="step.updated_at || step.update_time">
								<text class="time-label">审批时间：</text>
								<text class="time-value">{{ formatDate(step.updated_at || step.update_time) }}</text>
							</view>

							<!-- 审批意见 -->
							<view class="step-comment" v-if="step.comment">
								<text class="comment-label">审批意见：</text>
								<text class="comment-content">{{ step.comment }}</text>
							</view>

							<!-- 审批附件 -->
							<view class="step-attachments" v-if="step.attachments && step.attachments.length > 0">
								<text class="attachments-label">审批附件：</text>
								<view class="attachments-list">
									<view class="attachment-item" v-for="(file, fileIndex) in step.attachments"
										:key="fileIndex" @tap="previewFile(file)">
										<!-- 图片文件显示缩略图 -->
										<image v-if="isImageFile(file)" class="file-thumbnail" :src="file.url" mode="aspectFill" 
											@error="handleImageError" />
										<!-- 非图片文件显示图标 -->
										<text v-else class="file-icon">📎</text>
										<view class="file-info">
											<text class="file-name">{{ file.name }}</text>
										</view>
									</view>
								</view>
							</view>

							<!-- 当前步骤提示 -->
							<view class="current-step-indicator"
								v-if="step.status === 'pending' && isCurrentUserApprover(step)">
								<text class="indicator-text">👤 当前轮到您审批</text>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 审批操作区域（仅当当前用户是审批人且状态为待审批时显示） -->
		<view class="section approval-actions" v-if="isCurrentApprover && workflowStatus === 'pending'">
			<view class="section-title">审批操作</view>
			<view class="action-form">
				<view class="form-item">
					<text class="form-label">审批意见</text>
					<textarea class="form-textarea" v-model="approvalComment" placeholder="请输入审批意见（选填）"
						maxlength="500"></textarea>
					<text class="char-count">{{ approvalComment.length }}/500</text>
				</view>

				<view class="form-item">
					<UploadAttachments v-model="uploadedFiles" label="上传附件（选填）" :max-count="5"
						:file-types="['jpg', 'jpeg', 'png']" />
				</view>

				<view class="action-buttons">
					<button class="btn btn-approve" @tap="handleApprove">通过</button>
					<button class="btn btn-reject" @tap="handleReject">拒绝</button>
				</view>
			</view>
		</view>

		<!-- 入库操作区域（仅当采购审批通过后显示） -->
		<view class="section inventory-actions"
			v-if="workflowType === 'purchase' && workflowStatus === 'approved' && !hasInventoryRecord && canPerformInventory">
			<view class="section-title">采购入库操作</view>
			<view class="inventory-notice">
				<text class="notice-icon">📦</text>
				<text class="notice-text">采购审批已通过，请完成采购后填写物品入库单</text>
			</view>
			<view class="action-buttons">
				<button class="btn btn-inventory" @tap="showInventoryForm">填写入库单</button>
			</view>
		</view>

		<!-- 权限提示区域（当用户没有入库权限时显示） -->
		<view class="section inventory-permission-notice"
			v-if="workflowType === 'purchase' && workflowStatus === 'approved' && !hasInventoryRecord && !canPerformInventory">
			<view class="section-title">采购状态</view>
			<view class="permission-notice">
				<text class="notice-icon">⏳</text>
				<text class="notice-text">采购审批已通过，等待采购人员完成采购和入库操作</text>
			</view>
		</view>

		<!-- 入库记录显示（如果已有入库记录） -->
		<view class="section inventory-record" v-if="workflowType === 'purchase' && inventoryRecord">
			<view class="section-title">采购入库记录</view>
			<view class="inventory-info-card">
				<view class="info-item">
					<text class="label">入库单号</text>
					<text class="value">{{ inventoryRecord.inventory_no }}</text>
				</view>
				<view class="info-item">
					<text class="label">采购完成日期</text>
					<text class="value">{{ formatDate(inventoryRecord.purchase_complete_date) }}</text>
				</view>
				<view class="info-item">
					<text class="label">入库日期</text>
					<text class="value">{{ formatDate(inventoryRecord.inventory_date) }}</text>
				</view>
				<view class="info-item">
					<text class="label">采购人员</text>
					<text class="value">{{ inventoryRecord.purchaser }}</text>
				</view>
				<view class="info-item">
					<text class="label">入库人员</text>
					<text class="value">{{ inventoryRecord.inventory_person }}</text>
				</view>
				<view class="info-item">
					<text class="label">仓库位置</text>
					<text class="value">{{ inventoryRecord.warehouse_location }}</text>
				</view>
				<view class="info-item">
					<text class="label">物品总数</text>
					<text class="value">{{ inventoryRecord.total_items }}</text>
				</view>
				<view class="info-item">
					<text class="label">入库总金额</text>
					<text class="value">¥{{ inventoryRecord.total_amount }}</text>
				</view>
				<view class="info-item" v-if="inventoryRecord.purchase_remark">
					<text class="label">采购备注</text>
					<text class="value detail-text">{{ inventoryRecord.purchase_remark }}</text>
				</view>
				<view class="info-item" v-if="inventoryRecord.remark">
					<text class="label">入库备注</text>
					<text class="value detail-text">{{ inventoryRecord.remark }}</text>
				</view>
			</view>
		</view>

		<!-- 审批确认对话框 -->
		<uni-popup ref="approvalPopup" type="dialog">
			<uni-popup-dialog :type="approvalDialogType" :title="approvalDialogTitle" :content="approvalDialogContent"
				:before-close="true" @confirm="handleApprovalConfirm" @close="handleApprovalCancel"></uni-popup-dialog>
		</uni-popup>

		<!-- 加载中提示 -->
		<uni-popup ref="loadingPopup" type="center">
			<view class="loading-container">
				<view class="loading-spinner"></view>
				<text class="loading-text">加载中...</text>
			</view>
		</uni-popup>

		<!-- 入库表单弹窗 -->
		<uni-popup ref="inventoryPopup" type="center" :mask-click="false">
			<view class="inventory-popup-container">
				<view class="popup-header">
					<text class="popup-title">物品入库单</text>
					<text class="popup-close" @tap="closeInventoryForm">×</text>
				</view>
				<view class="popup-content">
					<InventoryForm @submit="handleInventorySubmit" @cancel="closeInventoryForm" />
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { onLoad, onShow } from '@dcloudio/uni-app'
import { workflowApi } from '@/common/api'
import { isLoggedIn, getCurrentUser } from '@/common/auth'
import { uiUtils } from '@/common/uiUtils'
import { formatFileSize, uploadAttachments } from '@/common/upload'
import InventoryForm from '@/components/InventoryForm.vue'
import UploadAttachments from '@/components/UploadAttachments.vue'

// 从uiUtils导入函数
const {
	getApplicationIcon,
	getStatusText,
	getWorkflowTypeText,
	getStatusClass
} = uiUtils

// 工作流状态函数
const getStepStatusClass = (status: string): string => {
	const statusMap: Record<string, string> = {
		'pending': 'pending',
		'approved': 'approved',
		'rejected': 'rejected',
		'canceled': 'canceled'
	}
	return statusMap[status] || 'pending'
}

const getStepStatusText = (status: string): string => {
	const statusMap: Record<string, string> = {
		'pending': '待审批',
		'approved': '已通过',
		'rejected': '已拒绝',
		'canceled': '已取消'
	}
	return statusMap[status] || '待审批'
}

// 页面参数
const instance_id = ref('')
const workflowType = ref('')
const stepId = ref('')
const mode = ref('view') // view 或 approval

// 数据状态
const isLoading = ref(false)
const hasLoaded = ref(false) // 添加标志防止重复加载
const applicationData = ref<any>({})
const workflowStatus = ref('pending')
const approvalSteps = ref<any[]>([])
const applicantInfo = ref<any>({})
const timeRange = ref('')
const applicationAttachments = ref<any[]>([])

// 审批操作相关
const approvalComment = ref('')
const uploadedFiles = ref<any[]>([])
const isCurrentApprover = ref(false)

// 审批对话框
const approvalPopup = ref<any>(null)
const loadingPopup = ref<any>(null)
const approvalDialogType = ref('info')
const approvalDialogTitle = ref('')
const approvalDialogContent = ref('')
const approvalAction = ref('')

// 入库相关
const inventoryPopup = ref<any>(null)
const inventoryRecord = ref<any>(null)
const hasInventoryRecord = computed(() => !!inventoryRecord.value)

// 检查是否有入库权限（采购人员或管理员）
const canPerformInventory = computed(() => {
	if (!isLoggedIn()) return false

	const currentUser = getCurrentUser()
	if (!currentUser || !currentUser.id) return false

	// 检查用户角色是否为采购人员
	if (currentUser.role === 'purchaser' || currentUser.role === 'procurement') {
		return true
	}

	// 管理员可以入库
	if (currentUser.role === 'admin') {
		return true
	}

	// 如果用户信息中没有明确角色，检查用户类型或部门
	if (currentUser.user_type === 'purchaser' || currentUser.department === '采购部') {
		return true
	}

	return false
})

// 加载工作流详情
const loadWorkflowDetail = async () => {
	console.log('loadWorkflowDetail 函数被调用')
	console.log('instance_id:', instance_id.value)
	console.log('workflowType:', workflowType.value)

	if (!instance_id.value || !workflowType.value) {
		console.log('参数错误：缺少 workflowId 或 workflowType')
		uni.showToast({
			title: '参数错误',
			icon: 'none'
		})
		return
	}

	isLoading.value = true
	if (loadingPopup.value) {
		loadingPopup.value.open()
	}

	try {
		console.log('开始调用 API 获取工作流详情')
		// 获取工作流详情
		const res: any = await workflowApi.getWorkflowInstance(instance_id.value)

		console.log('API 响应:', res)

		if (res.success && res.data) {
			// 使用第一个匹配的任务作为当前任务
			applicationData.value = res.data
			workflowStatus.value = applicationData.value.status || 'pending'

			// 提取申请人信息
			if (res.data.applicant) {
				applicantInfo.value = res.data.applicant
			}

			// 提取审批流程
			if (res.data.approval_process) {
				approvalSteps.value = res.data.approval_process
			}

			console.log('applicationAttachments', applicationAttachments.value, res.data.attachments)
			// 提取附件
			if (res.data.attachments && Array.isArray(res.data.attachments) && res.data.attachments.length > 0) {
				applicationAttachments.value = res.data.attachments.map((file: any) => {
					return ({
						name: file.file_name || file.name,
						url: file.url || file.file_url,
						size: formatFileSize(file.file_size || file.size),
						type: file.file_type || file.type
					})
				})
			} else {
				// 确保没有附件时初始化为空数组
				applicationAttachments.value = []
			}

			// 格式化时间范围
			timeRange.value = formatTimeRange(res.data)

			// 检查当前用户是否为审批人
			checkIfCurrentApprover()

			// 如果是采购审批且已通过，加载入库记录
			if (workflowType.value === 'purchase' && workflowStatus.value === 'approved') {
					loadInventoryRecord()
				}

				console.log('工作流详情加载完成:', res.data)
				hasLoaded.value = true // 标记已加载
			} else {
				console.log('API 返回数据格式不正确:', res)
				uni.showToast({
					title: res.message || '获取详情失败',
					icon: 'none'
				})
			}
		} catch (error) {
			console.error('获取工作流详情失败:', error)
			uni.showToast({
				title: '加载失败，请稍后重试',
				icon: 'none'
			})
		} finally {
			isLoading.value = false
			if (loadingPopup.value) {
				loadingPopup.value.close()
			}
		}
	}

// 检查当前用户是否为审批人
const checkIfCurrentApprover = () => {
		if (!isLoggedIn()) return

		const currentUser = getCurrentUser()
		if (!currentUser || !currentUser.id) return

		// 查找当前待审批的步骤
		const pendingStep = approvalSteps.value.find(step => step.status === 'pending')
		if (pendingStep && pendingStep.approver_id === currentUser.id) {
			isCurrentApprover.value = true
			stepId.value = pendingStep.id
		}
	}

	// 检查是否为当前用户的审批步骤
	const isCurrentUserApprover = (step: any): boolean => {
		if (!isLoggedIn()) return false

		const currentUser = getCurrentUser()
		if (!currentUser || !currentUser.id) return false

		return step.approver_id === currentUser.id || step.user_id === currentUser.id
	}

	// 加载入库记录
	const loadInventoryRecord = async () => {
		try {
			const res = await workflowApi.getInventoryRecord(instance_id.value)
			if (res.success && res.data) {
				inventoryRecord.value = res.data
			}
		} catch (error) {
			console.error('加载入库记录失败:', error)
		}
	}

	// 格式化时间范围
	const formatTimeRange = (data: any): string => {
		if (!data.business_data) return ''

		const businessData = data.business_data

		// 处理请假申请
		if (data.workflow_type === 'leave' && businessData.start_time && businessData.end_time) {
			return `${formatDate(businessData.start_time)} 至 ${formatDate(businessData.end_time)}`
		}

		// 处理出差申请
		if (data.workflow_type === 'businessTrip' && businessData.start_date && businessData.end_date) {
			return `${formatDate(businessData.start_date)} 至 ${formatDate(businessData.end_date)}`
		}

		// 处理用车申请
		if (data.workflow_type === 'vehicle' && businessData.use_time && businessData.return_time) {
			return `${formatDate(businessData.use_time)} 至 ${formatDate(businessData.return_time)}`
		}

		// 处理其他类型的申请
		if (businessData.start_time && businessData.end_time) {
			return `${formatDate(businessData.start_time)} 至 ${formatDate(businessData.end_time)}`
		}

		return ''
	}

	// 格式化日期
	const formatDate = (dateString: string) => {
		if (!dateString) return ''

		const date = new Date(dateString)
		const year = date.getFullYear()
		const month = String(date.getMonth() + 1).padStart(2, '0')
		const day = String(date.getDate()).padStart(2, '0')
		const hours = String(date.getHours()).padStart(2, '0')
		const minutes = String(date.getMinutes()).padStart(2, '0')

		return `${year}-${month}-${day} ${hours}:${minutes}`
	}

	// 判断是否为图片文件
	const isImageFile = (file: any): boolean => {
		if (!file || !file.name) return false
		
		const fileName = file.name.toLowerCase()
		const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp', 'svg']
		const extension = fileName.split('.').pop()
		
		return imageExtensions.includes(extension)
	}

	// 处理图片加载错误
	const handleImageError = (event: any) => {
		console.error('图片加载失败:', event)
		// 可以在这里添加默认图片或其他处理逻辑
	}

	// 预览文件
	const previewFile = (file: any) => {
		if (!file) {
			uni.showToast({
				title: '文件信息无效',
				icon: 'none'
			})
			return
		}

		// 获取文件URL，支持多种字段名
		const fileUrl = file.url || file.file_url || file.path
		if (!fileUrl) {
			uni.showToast({
				title: '文件地址无效',
				icon: 'none'
			})
			return
		}

		// 获取文件名，支持多种字段名
		const fileName = file.name || file.file_name || 'unknown'
		
		// 根据文件类型选择预览方式
		const fileType = fileName.split('.').pop()?.toLowerCase() || ''

		if (['jpg', 'jpeg', 'png', 'gif', 'webp'].includes(fileType)) {
			// 图片预览
			uni.previewImage({
				urls: [fileUrl],
				current: fileUrl,
				fail: (err: UniApp.GeneralCallbackResult) => {
					console.error('图片预览失败:', err)
					uni.showToast({
						title: '图片预览失败',
						icon: 'none'
					})
				}
			})
		} else {
			// 其他文件使用系统方式打开
			uni.openDocument({
				filePath: fileUrl,
				success: () => {
					console.log('打开文档成功')
				},
				fail: (err: UniApp.GeneralCallbackResult) => {
					console.error('打开文档失败:', err)
					uni.showToast({
						title: '无法打开此类型文件',
						icon: 'none'
					})
				}
			})
		}
	}



	// 上传文件
	const uploadAllFiles = async (): Promise<string[]> => {
		if (uploadedFiles.value.length === 0) return []
		const fileUrls: string[] = []

		try {
			if (loadingPopup.value) {
				loadingPopup.value.open()
			}

			const uploadedResults = await uploadAttachments(
				uploadedFiles.value,
				true, // 并行上传
				{}, // 无额外表单数据
				(current, total) => {
					console.log(`上传进度: ${current}/${total}`)
				}
			)

			uploadedResults.forEach(file => {
				if (file && file.url) {
					fileUrls.push(file.url)
				}
			})

			return fileUrls
		} catch (error) {
			console.error('上传文件失败:', error)
			uni.showToast({
				title: '文件上传失败',
				icon: 'none'
			})
			return []
		} finally {
			if (loadingPopup.value) {
				loadingPopup.value.close()
			}
		}
	}

	// 审批通过
	const handleApprove = () => {
		approvalAction.value = 'approve'
		approvalDialogType.value = 'success'
		approvalDialogTitle.value = '审批通过'
		approvalDialogContent.value = '确认通过此申请吗？'
		if (approvalPopup.value) {
			approvalPopup.value.open()
		}
	}

	// 审批拒绝
	const handleReject = () => {
		approvalAction.value = 'reject'
		approvalDialogType.value = 'error'
		approvalDialogTitle.value = '审批拒绝'
		approvalDialogContent.value = '确认拒绝此申请吗？'
		if (approvalPopup.value) {
			approvalPopup.value.open()
		}
	}

	// 确认审批操作
	const handleApprovalConfirm = async () => {
		try {
			// 先提交审批操作
			let res
			if (approvalAction.value === 'approve') {
				res = await workflowApi.approve(instance_id.value, approvalComment.value)
			} else {
				res = await workflowApi.reject(instance_id.value, approvalComment.value)
			}

			if (res.success) {
				// 审批成功后，再上传附件
				if (uploadedFiles.value.length > 0) {
					try {
						const attachmentUrls = await uploadAllFiles()

						// 如果有附件上传成功，显示成功提示
						if (attachmentUrls.length > 0) {
							console.log('附件上传成功:', attachmentUrls)
							// 注意：由于审批已提交，附件可能需要通过其他方式关联到审批记录
							// 这里可以根据实际业务需求进行调整
						}
					} catch (uploadError) {
						console.error('附件上传失败:', uploadError)
						// 附件上传失败不影响审批结果，只显示提示
						uni.showToast({
							title: '审批成功，但附件上传失败',
							icon: 'none'
						})
					}
				}

				uni.showToast({
					title: approvalAction.value === 'approve' ? '已通过' : '已拒绝',
					icon: 'success'
				})

				// 刷新页面数据
				setTimeout(() => {
					loadWorkflowDetail()
				}, 1500)

				// 返回待办列表
				setTimeout(() => {
					uni.navigateBack()
				}, 2000)
			} else {
				uni.showToast({
					title: res.message || '操作失败',
					icon: 'none'
				})
			}
		} catch (error) {
			console.error('审批操作失败:', error)
			uni.showToast({
				title: '网络错误，请稍后重试',
				icon: 'none'
			})
		} finally {
			if (approvalPopup.value) {
				approvalPopup.value.close()
			}
		}
	}

	// 取消审批操作
	const handleApprovalCancel = () => {
		if (approvalPopup.value) {
			approvalPopup.value.close()
		}
	}

	// 显示入库表单
	const showInventoryForm = () => {
		if (inventoryPopup.value) {
			inventoryPopup.value.open()
		}
	}

	// 关闭入库表单
	const closeInventoryForm = () => {
		if (inventoryPopup.value) {
			inventoryPopup.value.close()
		}
	}

	// 处理入库提交
	const handleInventorySubmit = async (inventoryData: any) => {
		try {
			// 添加工单ID到入库数据
			const submitData = {
				...inventoryData,
				workflow_id: instance_id.value,
				workflow_type: workflowType.value
			}

			// 调用入库API
			const res = await workflowApi.submitInventory(submitData)

			if (res.success) {
				uni.showToast({
					title: '入库成功',
					icon: 'success'
				})

				// 更新入库记录
				inventoryRecord.value = submitData

				// 关闭弹窗
				closeInventoryForm()

				// 刷新页面数据
				setTimeout(() => {
					loadWorkflowDetail()
				}, 1500)
			} else {
				uni.showToast({
					title: res.message || '入库失败',
					icon: 'none'
				})
			}
		} catch (error) {
			console.error('入库提交失败:', error)
			uni.showToast({
				title: '网络错误，请稍后重试',
				icon: 'none'
			})
		}
	}

	// 页面加载
	onLoad((options) => {
		console.log('Approval process page options:', options)

		if (options.id) {
			instance_id.value = options.id
		}

		if (options.type) {
			workflowType.value = options.type
		}

		if (options.step_id) {
			stepId.value = options.step_id
		}

		if (options.mode) {
			mode.value = options.mode
		}

		// 加载工作流详情
		loadWorkflowDetail()
	})

	// 下拉刷新处理函数
	const onPullDownRefresh = () => {
		console.log('下拉刷新')
		if (instance_id.value && workflowType.value) {
			loadWorkflowDetail().finally(() => {
				uni.stopPullDownRefresh()
			})
		} else {
			uni.stopPullDownRefresh()
		}
	}


	// 页面显示时刷新数据
	onShow(() => {
		// 只有在有参数且已经加载过数据时才刷新数据
		if (instance_id.value && workflowType.value && hasLoaded.value && !isLoading.value) {
			loadWorkflowDetail()
		}
	})
</script>

<style>
.approval-process-container {
	padding: 20rpx;
	background-color: #f5f6fa;
	min-height: 100vh;
}

/* 页面头部 */
.header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	background-color: #fff;
	border-radius: 12rpx;
	padding: 24rpx;
	margin-bottom: 20rpx;
	box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
}

.title-container {
	display: flex;
	align-items: center;
	gap: 16rpx;
}

.icon {
	font-size: 40rpx;
}

.title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
}

.status-badge {
	padding: 8rpx 16rpx;
	border-radius: 20rpx;
	font-size: 24rpx;
	font-weight: bold;
}

.status-badge.pending {
	background-color: #e3f2fd;
	color: #2196f3;
}

.status-badge.approved {
	background-color: #e8f5e8;
	color: #4caf50;
}

.status-badge.rejected {
	background-color: #ffebee;
	color: #f44336;
}

/* 通用区块样式 */
.section {
	margin-bottom: 20rpx;
}

.section-title {
	font-size: 30rpx;
	font-weight: bold;
	color: #333;
	margin-bottom: 16rpx;
	padding-left: 8rpx;
}

/* 基本信息卡片 */
.basic-info .info-card {
	background-color: #fff;
	border-radius: 12rpx;
	padding: 24rpx;
	box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
}

.info-item {
	display: flex;
	justify-content: space-between;
	align-items: flex-start;
	margin-bottom: 16rpx;
}

.info-item:last-child {
	margin-bottom: 0;
}

.label {
	font-size: 28rpx;
	color: #666;
	flex-shrink: 0;
	width: 140rpx;
}

.value {
	font-size: 28rpx;
	color: #333;
	flex: 1;
	text-align: right;
}

.detail-text {
	text-align: left;
	line-height: 1.5;
}

/* 申请内容上下布局样式 */
.detail-item {
	flex-direction: column;
	align-items: flex-start;
}

.detail-item .label {
	width: auto;
	margin-bottom: 12rpx;
}

.detail-content {}

.detail-content .detail-text {
	display: block;
	width: 100%;
	/* padding: 16rpx; */
	/* border-radius: 8rpx; */
	font-size: 28rpx;
}

/* 申请附件列表样式 */
.basic-info .attachments-list {
	display: flex;
	flex-direction: column;
	gap: 12rpx;
	width: 100%;
}

.basic-info .attachment-item {
	display: flex;
	align-items: center;
	gap: 12rpx;
	padding: 16rpx;
	background-color: #f8f9fa;
	border: 1rpx solid #e9ecef;
	border-radius: 8rpx;
	transition: background-color 0.2s;
}

.basic-info .attachment-item:active {
	background-color: #e9ecef;
}

.basic-info .file-thumbnail {
	width: 80rpx;
	height: 80rpx;
	border-radius: 6rpx;
	flex-shrink: 0;
	background-color: #f0f0f0;
}

.basic-info .file-icon {
	font-size: 24rpx;
	color: #6c757d;
	width: 80rpx;
	height: 80rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	background-color: #f0f0f0;
	border-radius: 6rpx;
	flex-shrink: 0;
}

.basic-info .file-info {
	flex: 1;
	display: flex;
	flex-direction: column;
	gap: 4rpx;
}

.basic-info .file-name {
	font-size: 26rpx;
	color: #333;
	word-break: break-all;
	line-height: 1.3;
}

.basic-info .file-size {
	font-size: 22rpx;
	color: #6c757d;
}

/* 审批流程时间线 */
.approval-timeline .timeline-container {
	background-color: #fff;
	border-radius: 12rpx;
	padding: 24rpx;
	box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
}

.loading-state,
.empty-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 60rpx 0;
}

.loading-text,
.empty-text {
	font-size: 28rpx;
	color: #999;
	margin-top: 16rpx;
}

.empty-icon {
	font-size: 60rpx;
	color: #ccc;
}

.timeline {
	position: relative;
}

.timeline-item {
	position: relative;
	padding-left: 60rpx;
	margin-bottom: 40rpx;
}

.timeline-item:last-child {
	margin-bottom: 0;
}

.timeline-line {
	position: absolute;
	left: 20rpx;
	top: 40rpx;
	bottom: -40rpx;
	width: 2rpx;
	background-color: #e0e0e0;
}

.timeline-item.last-item .timeline-line {
	display: none;
}

.step-marker {
	position: absolute;
	left: 0;
	top: 10rpx;
	width: 40rpx;
	height: 40rpx;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	background-color: #e0e0e0;
}

.step-marker.approved {
	background-color: #4caf50;
}

.step-marker.rejected {
	background-color: #f44336;
}

.step-marker.pending {
	background-color: #2196f3;
}

.marker-icon {
	color: white;
	font-size: 20rpx;
	font-weight: bold;
}

.step-content {
	background-color: #fafafa;
	border-radius: 12rpx;
	padding: 20rpx;
	border-left: 4rpx solid #e0e0e0;
}

.timeline-item.current-step .step-content {
	border-left-color: #2196f3;
	background-color: #e3f2fd;
}

.timeline-item.completed-step .step-content {
	border-left-color: #4caf50;
	background-color: #e8f5e8;
}

.timeline-item.rejected-step .step-content {
	border-left-color: #f44336;
	background-color: #ffebee;
}

.step-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 12rpx;
}

.step-info {
	display: flex;
	flex-direction: column;
	gap: 4rpx;
}

.step-name {
	font-size: 30rpx;
	font-weight: bold;
	color: #333;
}

.step-position {
	font-size: 24rpx;
	color: #666;
}

.step-status {
	font-size: 26rpx;
	font-weight: bold;
}

.step-status.approved {
	color: #4caf50;
}

.step-status.rejected {
	color: #f44336;
}

.step-status.pending {
	color: #2196f3;
}

.step-time {
	display: flex;
	align-items: center;
	gap: 8rpx;
	margin-bottom: 12rpx;
}

.time-label {
	font-size: 24rpx;
	color: #666;
}

.time-value {
	font-size: 24rpx;
	color: #333;
}

.step-comment {
	margin-bottom: 12rpx;
}

.comment-label {
	font-size: 24rpx;
	color: #666;
	margin-bottom: 8rpx;
	display: block;
}

.comment-content {
	font-size: 26rpx;
	color: #333;
	background-color: #f0f0f0;
	padding: 12rpx;
	border-radius: 8rpx;
	line-height: 1.4;
}

.step-attachments {
	margin-bottom: 12rpx;
}

.attachments-label {
	font-size: 24rpx;
	color: #666;
	margin-bottom: 8rpx;
	display: block;
}

.attachments-list {
	display: flex;
	flex-direction: column;
	gap: 8rpx;
}

.attachment-item {
	display: flex;
	align-items: center;
	gap: 8rpx;
	padding: 8rpx 12rpx;
	background-color: #f0f0f0;
	border-radius: 6rpx;
}

.file-thumbnail {
	width: 60rpx;
	height: 60rpx;
	border-radius: 4rpx;
	flex-shrink: 0;
	background-color: #e0e0e0;
}

.file-icon {
	font-size: 20rpx;
	width: 60rpx;
	height: 60rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	background-color: #e0e0e0;
	border-radius: 4rpx;
	flex-shrink: 0;
}

.file-info {
	flex: 1;
	display: flex;
	flex-direction: column;
	gap: 2rpx;
}

.file-name {
	font-size: 24rpx;
	color: #333;
	line-height: 1.2;
}

.current-step-indicator {
	margin-top: 12rpx;
	padding: 8rpx 12rpx;
	background-color: #fff3cd;
	border: 1rpx solid #ffeaa7;
	border-radius: 6rpx;
}

.indicator-text {
	font-size: 24rpx;
	color: #856404;
}

/* 审批操作区域 */
.approval-actions .action-form {
	background-color: #fff;
	border-radius: 12rpx;
	padding: 24rpx;
	box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
}

.form-item {
	margin-bottom: 24rpx;
}

.form-label {
	font-size: 28rpx;
	color: #333;
	margin-bottom: 12rpx;
	display: block;
}

.form-textarea {
	width: 100%;
	box-sizing: border-box;
	height: 200rpx;
	background-color: #fafafa;
	border: 1rpx solid #e0e0e0;
	border-radius: 8rpx;
	padding: 16rpx;
	font-size: 28rpx;
	resize: none;
}

.char-count {
	font-size: 24rpx;
	color: #999;
	text-align: right;
	margin-top: 8rpx;
}



.action-buttons {
	display: flex;
	gap: 20rpx;
	margin-top: 32rpx;
}

.btn {
	flex: 1;
	padding: 2rpx 20rpx;
	border-radius: 8rpx;
	font-size: 30rpx;
	font-weight: bold;
	border: none;
}

.btn-approve {
	background-color: #2B5BA1;
	color: white;
}

.btn-reject {
	background-color: white;
	color: #f44336;
	border: 1rpx solid #f44336;
}

/* 入库操作区域 */
.inventory-actions .inventory-notice {
	display: flex;
	align-items: center;
	gap: 12rpx;
	padding: 16rpx;
	background-color: #e3f2fd;
	border-radius: 8rpx;
	margin-bottom: 20rpx;
}

.notice-icon {
	font-size: 32rpx;
}

.notice-text {
	font-size: 26rpx;
	color: #1976d2;
}

.btn-inventory {
	background-color: #4caf50;
	color: white;
}

/* 权限提示区域 */
.inventory-permission-notice .permission-notice {
	display: flex;
	align-items: center;
	gap: 12rpx;
	padding: 16rpx;
	background-color: #fff3cd;
	border-radius: 8rpx;
	margin-bottom: 20rpx;
	border: 1rpx solid #ffeaa7;
}

/* 入库记录显示 */
.inventory-record .inventory-info-card {
	background-color: #fff;
	border-radius: 12rpx;
	padding: 24rpx;
	box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
}

/* 入库表单弹窗 */
.inventory-popup-container {
	width: 90vw;
	max-height: 80vh;
	background-color: #fff;
	border-radius: 12rpx;
	overflow: hidden;
}

.popup-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 24rpx;
	border-bottom: 1rpx solid #e0e0e0;
	background-color: #f5f6fa;
}

.popup-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
}

.popup-close {
	font-size: 40rpx;
	color: #999;
	padding: 8rpx;
}

.popup-content {
	max-height: calc(80vh - 80rpx);
	overflow-y: auto;
}

/* 加载提示样式 */
.loading-container {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 60rpx 40rpx;
	background: rgba(255, 255, 255, 0.95);
	border-radius: 16rpx;
	min-width: 200rpx;
}

.loading-spinner {
	width: 60rpx;
	height: 60rpx;
	border: 4rpx solid #f3f3f3;
	border-top: 4rpx solid #2B5BA1;
	border-radius: 50%;
	animation: spin 1s linear infinite;
	margin-bottom: 20rpx;
}

.loading-text {
	font-size: 28rpx;
	color: #666;
}

@keyframes spin {
	0% {
		transform: rotate(0deg);
	}

	100% {
		transform: rotate(360deg);
	}
}
</style>